"use client";
import {
  PageContainer,
  ProForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormTreeSelect,
} from "@ant-design/pro-components";
import { useRequest } from "ahooks";
import { Button, Card, Col, message, Row, Space } from "antd";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { useState } from "react";
import { RollbackOutlined } from "@ant-design/icons";
import {
  addDeptApi,
  updateDeptApi,
  getDeptApi,
  getDeptTreeApi,
} from "@/lib/api/system/dept";
import { Dept } from "@/lib/api/system/dept.d";

export default function Page() {
  const { type } = useParams();
  const router = useRouter();
  const [deptId, setDeptId] = useState<number>(0);
  const params = useSearchParams();
  const deptid = params.get("deptId");

  const title = type === "add" ? "新增部门" : "修改部门";

  const { run: addDept, loading: addDeptLoading } = useRequest(addDeptApi, {
    manual: true,
    onSuccess: () => {
      message.success("新增成功");
      router.back();
    },
    onError: (error: any) => {
      message.error(error.msg);
    },
  });

  const { run: updateDept, loading: updateDeptLoading } = useRequest(
    (params) => updateDeptApi({ ...params, deptId: deptId }),
    {
      manual: true,
      onSuccess: () => {
        message.success("修改成功");
        router.back();
      },
      onError: (error: any) => {
        message.error(error.msg);
      },
    },
  );

  const extraProps =
    type !== "add"
      ? {
          request: async () => {
            const res = await getDeptApi(deptid as string);
            setDeptId(res.data.deptId);
            return res.data;
          },
        }
      : {
          defaultFormValues: {
            parentId: 101,
          },
        };

  return (
    <PageContainer
      title={title}
      extra={
        <Button icon={<RollbackOutlined />} onClick={() => router.back()}>
          返回
        </Button>
      }
    >
      <Card>
        <ProForm
          layout="horizontal"
          submitter={{
            render: (_, dom) => {
              return (
                <Row>
                  <Col span={14} offset={4}>
                    <Space>{dom}</Space>
                  </Col>
                </Row>
              );
            },
            searchConfig: { submitText: "保存" },
          }}
          className="max-w-[800px] mx-auto my-10"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 14 }}
          loading={addDeptLoading || updateDeptLoading}
          onFinish={async (values: Dept) => {
            if (type === "add") {
              await addDept(values);
            } else {
              await updateDept(values);
            }
          }}
          {...extraProps}
        >
          <ProFormTreeSelect
            name="parentId"
            label="上级部门"
            key="id"
            fieldProps={{
              fieldNames: { label: "label", value: "id" },
            }}
            request={async () => {
              const res = await getDeptTreeApi();
              return res.data;
            }}
            required
            rules={[{ required: true, message: "请输入字典名称" }]}
          />
          <ProFormText
            name="deptName"
            label="部门名称"
            required
            rules={[{ required: true, message: "请输入字典类型" }]}
          />
          <ProFormDigit
            min={0}
            max={100}
            fieldProps={{
              precision: 0,
            }}
            name="orderNum"
            label="排序"
            rules={[{ required: true, message: "请输入排序" }]}
          />
          <ProFormText name="deptCategory" label="类型编码" />
          <ProFormText name="leader" label="负责人" />
          <ProFormText name="phone" label="联系电话" />
          <ProFormText name="email" label="邮箱" />
          <ProFormSelect
            name="status"
            label="部门状态"
            options={[
              { label: "正常", value: "0" },
              { label: "停用", value: "1" },
            ]}
          />
        </ProForm>
      </Card>
    </PageContainer>
  );
}
